import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_ahj_app/base/basewidget/HttpUtils/HttpBaseConst.dart';
import 'package:flutter_ahj_app/base/basewidget/HttpUtils/HttpOpenBaseConst.dart';
import 'package:flutter_ahj_app/base/basewidget/view/BaseWidget.dart';
import 'package:flutter_ahj_app/base/basewidget/view/DownFilesUtils.dart';
import 'package:flutter_ahj_app/base/basewidget/viewmodel/WebViewModel.dart';
import 'package:flutter_ahj_app/base/cunchu/UserInfoUtils.dart';
import 'package:flutter_ahj_app/base/pluglin/wxplulin/WxJumpUtils.dart';
import 'package:flutter_ahj_app/base/utils/ShowFiles/zjTopBar.dart';
import 'package:flutter_ahj_app/base/utils/ToastUtils.dart';
import 'package:flutter_ahj_app/base/utils/permission/PerUtils.dart';
import 'package:flutter_ahj_app/base/utils/permission/SelectPicUtils.dart';
import 'package:flutter_ahj_app/base/utils/screen_util.dart';
import 'package:flutter_ahj_app/base/utils/textUtils.dart';
import 'package:flutter_ahj_app/base/values/SQColor.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:permission_handler/permission_handler.dart';

class WebViewUntil extends BaseStatefulWidget {
  Map<String, String> args;
  String rightText;

  WebViewUntil({Key key, this.args});

  @override
  State<StatefulWidget> initState() {
    return _WebViewUntilState();
  }
}

class _WebViewUntilState extends BaseState<WebViewModel, WebViewUntil> {
  WebViewController _webViewController; // 添加一个controller
  bool isSetCookie = false;
  BuildContext _mcontext;
  List imageUrls; // 选择的图片
  bool _isJoinIn = false;
  String _teamId = "";

  JavascriptChannel _JsBridge(BuildContext context) => JavascriptChannel(
      name: 'ehs', // 与h5 端的一致 不然收不到消息
      onMessageReceived: (JavascriptMessage message) async {
//        print("object1111111111111111");
        print(message.message);
//        {"fileName":"气瓶安全监察规定（2015年）.docx","fileUrl":"https://zhishi.anhuanjia.com/m/GetAhjFile.aspx?fileId=e96871d9-9f14-45ec-9287-8c36460ec276"}

        var filePath = json.decode(message.message);
        if (filePath["type"] != null &&
            filePath["certificate"] != "" &&
            filePath["certificate"] != null) {
          //证书分享的

          if (filePath["shareType"] == "01") {
            Map map = new Map();
            map["url"] = filePath["shareUrl"];
            map["shareName"] = '';
            map["description"] = '';
            map["sharType"] = '0';
            WxJumpUtils.wxSharePicProgram(map);
          } else if (filePath["shareType"] == "02") {
            Map map = new Map();
            map["url"] = filePath["shareUrl"];
            map["shareName"] = '';
            map["description"] = '';
            map["sharType"] = '1';
            WxJumpUtils.wxSharePicProgram(map);
          } else if (filePath["shareType"] == "03") {
            String data = filePath["shareUrl"];
            String data1 = filePath["fileName"];
            DownFilesUtils.downLoad(context, data1, data);
          }
        } else if (filePath["type"] != null &&
            filePath["type"] == "downLoadFile") {
          String data = filePath["fileUrl"];
          String data1 = filePath["fileName"];
          DownFilesUtils.downLoad(context, data1, data);
        } else if (filePath["type"] != null && filePath["type"] == "close") {
          _goToRoot();
        } else if (filePath["type"] != null &&
            filePath["type"] == "takePhoto") {
          _pickImage();
        } else if (filePath["type"] != null &&
            filePath["type"] == "jumpToWebView") {
          Navigator.pushNamed(context, "/WebViewUntil",
              arguments: {"title": "在线签署", "url": filePath["url"].toString()});
        } else {
          String data = filePath["fileUrl"];
          String data1 = filePath["fileName"];
          HttpBaseConst.sessionId = filePath["sessionId"];
          DownFilesUtils.downLoad(context, data1, data);
        }

//        Navigator.pushNamed(context, "/regist",
//            arguments: RegistViewPage(phone: messagebean.value));
      });

// 图片���择弹框
  _pickImage() async {
    String result = await PerUtils.checkPermission(
        context, [Permission.camera, Permission.photos]);
    if (result == "2") {
      return;
    } else if (result == "0") {
      return ToastUtils.showToast('请开启手机相机、相册权限');
    } else {
      FocusScope.of(context).requestFocus(FocusNode());
      showDialog<bool>(
        context: context,
        builder: (BuildContext context) {
          return new SimpleDialog(
            title: new Text('选择照片'),
            children: <Widget>[
              new SimpleDialogOption(
                child: new InkWell(
                  child: new Container(
                    child: new Text(
                      '照相',
                      style: new TextStyle(fontSize: 16),
                    ),
                    height: 48,
                    alignment: Alignment.centerLeft,
                  ),
                ),
                onPressed: () {
                  onSelectPicClick("0");
                  Navigator.of(context).pop(true);
                },
              ),
              new SimpleDialogOption(
                child: new InkWell(
                  child: new Container(
                    child: new Text(
                      '从相册选择',
                      style: new TextStyle(fontSize: 16),
                    ),
                    height: 48,
                    alignment: Alignment.centerLeft,
                  ),
                ),
                onPressed: () {
                  onSelectPicClick("1");
                  Navigator.of(context).pop(true);
                },
              ),
            ],
          );
        },
      );
    }
  }

  void onSelectPicClick(String type) async {
    List result;
    Map<String, String> map = {"count": '1', "adress": ""};
    if ("0" == type) {
      //照相
      result = await SelectPicUtils.getTakePic(map);
      print(result[0]);
    } else if ("1" == type) {
      //选择图片
      result = await SelectPicUtils.getSelectPic(map);
    }

    
    // setState(() {

    // _orginImageUrls.clear();
    // result.forEach((f) {
    //   widget.imageUrls.add(f);
    // });

    // setState(() {
    //   widget.imageUrls = result;
    // });

    // _upLoadImage(result: result);
  }

  @override
  void initState() {
    super.initState();
    print('当前页面url-----${widget.args['url']}');
    if (Platform.isAndroid) WebView.platform = SurfaceAndroidWebView();
    Future.delayed(Duration.zero, () {
    });
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
  }

  @override
  Widget initWidget() {
    _mcontext = context;
    return WillPopScope(
      child: Scaffold(
        // resizeToAvoidBottomPadding: true,
        appBar: widget.args['url'].contains('noAppBar')
            ? null
            : ZJTopBar(
                elevation: 0,
                title: widget.args["title"],
                leftButtonIcon: Icons.arrow_back,
                onLeftButtonIconClick: () => _goBack(),
                rightButtonText: widget.args["rightText"] == null
                    ? ''
                    : widget.args["rightText"],
                rightButtonTextColor: widget.args["rightText"] == null
                    ? SQColor.theme_color
                    : SQColor.black_333333,
                onRightButtonClick: () {
                  if (widget.args['type'] == '安环云教') {
                    if (widget.args["rightText"] != null) {
                      if (widget.args["rightText"] == "奖励明细") {
                        Navigator.pushNamed(context, "/WebViewUntil",
                            arguments: {
                              "title": "奖励明细",
                              "url": "${HttpOpenBaseConst.zhaoMuUrl}" +
                                  "promotion/ahyj/reward" +
                                  "?ahj_token=${UserInfoUtils.getUserToken()}",
                            });
                      }
                    }
                  } else {
                    if (widget.args["rightText"] != null) {
                      if (widget.args["rightText"] == "分享") {
                        Map map = new Map();
                        map["url"] = widget.args["url"];
                        map["shareName"] = widget.args["shareName"] ?? '';
                        map["description"] = widget.args["description"] ?? '';

                        WxJumpUtils.wxShareApiMap(map);
                      } else if (widget.args["rightText"] == "活动规则") {
                        Navigator.pushNamed(context, "/WebViewUntil",
                            arguments: {
                              "title": "活动规则",
                              "url": "${HttpOpenBaseConst.zhaoMuUrl}" +
                                  "recruit/activityRules" +
                                  "?ahj_token=${UserInfoUtils.getUserToken()}",
                            });
                      } else if (widget.args["rightText"] == "查看订单") {
                        Navigator.pushNamed(context, "/XKYOrderListPage", arguments: '1');
                      } else if (widget.args["rightText"] == "奖励明细") {
                        Navigator.pushNamed(context, "/WebViewUntil",
                            arguments: {
                              "title": "奖励明细",
                              "url": HttpOpenBaseConst.zhaoMuUrl +
                                  "promotion/xzy/reward" +
                                  "?ahj_token=${UserInfoUtils.getUserToken()}",
                            });
                      } else if (widget.args["rightText"] == "推广订单") {
                        Navigator.pushNamed(context, "/XKYOrderListPage", arguments: '2');
                      } 
                    }
                  }
                }).create(),
        body: Container(
            width: ScreenUtil.getScreenW(context),
            height: ScreenUtil.getScreenH(context),
                margin: EdgeInsets.fromLTRB(0, 0, 0, 0),
                child: Column(
                  children: [
                    Expanded(
                      child: WebView(
                        javascriptMode: JavascriptMode.unrestricted,
                        // initialUrl: widget.args["url"],
//                  initialUrl: UserInfoUtils.getUserKFAdress(),

                        debuggingEnabled: true,
                        onPageFinished: (val) {
                          if (TextUtils.getStr(UserInfoUtils.getUserToken()) !=
                                  "" &&
                              !isSetCookie) {
                            _setCookie();
                          }
                        },
                        onWebViewCreated: (web) {
                          _webViewController = web;
                          Map<String, String> headers = {
                            "referer": 'https//api.anhuanjia.com'
                          };
                          _webViewController.loadUrl(widget.args['url'],
                              headers: headers,
                              httpBody: widget.args['httpBody']);
                        },
                        // , httpBody: widget.args['httpBody']
                        javascriptChannels: <JavascriptChannel>[
                          _JsBridge(context) // 与h5 通信
                        ].toSet(),
                        userAgent: Platform.isAndroid
                            ? "Mozilla/5.0 (Linux; Android 11; Pixel 5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.91 Mobile Safari/537.36 ahjapp"
                            : "Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1 ahjapp",
                        // addUserAgent:"ahjapp",
//                //JS执行模式 是否允许JS执行e
//                javascriptMode: JavascriptMode.unrestricted,
                      ),
                    )
                  ],
                )),
      ),
      onWillPop: () => _goBack(),
    );
  }

  _setCookie() async {
//    CookieManager cm = CookieManager();
//    await cm.clearCookies();
    _webViewController.evaluateJavascript(
        'document.cookie = "__sid=${UserInfoUtils.getSID()}; path=/;domain=.anhuanjia.com"');
    _webViewController.evaluateJavascript(
        'document.cookie = "_mid=${UserInfoUtils.getMID()}; path=/;domain=.anhuanjia.com"');
    _webViewController.evaluateJavascript(
        'document.cookie = "apptype=1; path=/;domain=.anhuanjia.com"');
//    _webViewController.evaluateJavascript(
//        'document.cookie = "ASP.NET_SessionId=${HttpBaseConst.sessionId}; path=/;domain=.anhuanjia.com"');
    isSetCookie = true;
    _webViewController.reload();
  }

  _goToRoot() {
    Navigator.pop(context);
  }

  _goBack() {
    if (_webViewController != null) {
      _webViewController.canGoBack().then((res) {
        print(res);
        if (res) {
          _webViewController.goBack();
        } else {
          Navigator.pop(context);
        }
      });
    } else {
      Navigator.pop(context);
    }
  }

  static DateTime _lastTime;
  preventDoubleTap({int interval}) {
    DateTime _nowTime = DateTime.now();
    if (_lastTime == null ||
        _nowTime.difference(_lastTime) >
            Duration(milliseconds: interval ?? 600)) {
      _lastTime = _nowTime;
      return true;
    } else {
      _lastTime = _nowTime;
      return false;
    }
  }
}
